package bamin.com.bamindaijia.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.IsMobileNOorPassword;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.Invoice;
import bamin.com.bamindaijia.model.Order;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.util.ConvertUtils;
import cz.msebera.android.httpclient.Header;

public class InvoiceAddressActivity extends ZjbBaseActivity implements View.OnClickListener {

    private EditText mEdit_company_name;
    private TextView mTv_invoice_all_price;
    private EditText mEdit_addressee;
    private TextView mTv_province;
    private TextView mTv_city;
    private TextView mTv_town;
    private Button mButton_sure;
    private EditText mEdit_detailed_address;
    private EditText mEdit_phonenum;
    private HashMap<Integer, Order> mInvoicesHash = new HashMap<>();
    private String mCompanyName;
    private String mAddressee;
    private String mPhoneNum;
    private String mProvince;
    private String mDetailedAddress;
    private String mEmail;
    private String mCity;
    private String mTown;
    private double mAllMoney;
    private String mOrderIds;
    private String mBasicAddress;
    private Integer mCustomerId;
    private String mCustomerName;
    private String mCustomerPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invoice_address);
        init();
    }

    @Override
    protected void initData() {
        if (mInvoicesHash.size() > 0) {

            StringBuffer mOrderIdsb = new StringBuffer();

            Iterator<Map.Entry<Integer, Order>> iterator = mInvoicesHash.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Integer, Order> next = iterator.next();
                Order value = next.getValue();
                int orderId = value.getId();
                mOrderIdsb.append(orderId).append(",");

                mCustomerId = value.getCustomerId();
                mCustomerName = value.getCustomerName();
                mCustomerPhone = value.getCustomerPhone();
            }
            mOrderIds = mOrderIdsb.toString();
            mOrderIds = mOrderIds.substring(0, mOrderIds.length() - 1);
        }

    }

    @Override
    protected void initViews() {
        mTv_invoice_all_price.setText(mAllMoney + "");
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        mButton_sure.setOnClickListener(this);
        findViewById(R.id.rela_choose_address).setOnClickListener(this);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mInvoicesHash = (HashMap<Integer, Order>) intent.getSerializableExtra(Constant.INTENT_KEY.INVOICE);
        mAllMoney = intent.getDoubleExtra(Constant.INTENT_KEY.INVOICE_MONEY, 0.00);
//        mUserId = intent.getIntExtra(Constant.INTENT_KEY.USER_ID, 0);

    }

    @Override
    protected void findID() {
        mEdit_company_name = (EditText) findViewById(R.id.edit_company_name);
        mEdit_addressee = (EditText) findViewById(R.id.edit_addressee);
        mEdit_detailed_address = (EditText) findViewById(R.id.edit_detailed_address);
        mEdit_phonenum = (EditText) findViewById(R.id.edit_phonenum);
        mTv_invoice_all_price = (TextView) findViewById(R.id.tv_invoice_all_price);
        mTv_province = (TextView) findViewById(R.id.tv_province);
        mTv_city = (TextView) findViewById(R.id.tv_city);
        mTv_town = (TextView) findViewById(R.id.tv_town);
        mButton_sure = (Button) findViewById(R.id.button_sure);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.rela_choose_address:
                showAddressChoose();
                break;
            case R.id.button_sure:


                mCompanyName = mEdit_company_name.getText().toString().trim();
                mAddressee = mEdit_addressee.getText().toString().trim();
                mPhoneNum = mEdit_phonenum.getText().toString().trim();
                mProvince = mTv_province.getText().toString().trim();
                mCity = mTv_city.getText().toString().trim();
                mTown = mTv_town.getText().toString().trim();
                mDetailedAddress = mEdit_detailed_address.getText().toString().trim();

                if (TextUtils.isEmpty(mCompanyName)) {
                    mEdit_company_name.setError("公司抬头不能为空");
                } else if (TextUtils.isEmpty(mAddressee)) {
                    mEdit_addressee.setError("收件人不能为空");
                } else if (TextUtils.isEmpty(mPhoneNum)) {
                    mEdit_phonenum.setError("联系电话不能为空");
                } else if (!IsMobileNOorPassword.isMobileNO(mPhoneNum)) {
                    mEdit_phonenum.setError("联系电话填写错误");
                } else if (mProvince.equals("请选择")) {
                    Toast.makeText(InvoiceAddressActivity.this, "请选择所在地区", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(mDetailedAddress)) {
                    mEdit_detailed_address.setError("详细地址不能为空");
                } else {
                    uploadInvoice();
                }

                break;
        }

    }

    /**
     * 提交订单
     */
    private void uploadInvoice() {
        String mAddress = mBasicAddress + mDetailedAddress;

        String url = Constant.Url.APPLY_ORDER_RECEIPT;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("customerId", mCustomerId);//用户ID
        params.put("customerName", mCustomerName);//乘客名
        params.put("customerPhone", mCustomerPhone);//乘客手机
        params.put("receiptTitle", mCompanyName);//公司抬头
//        params.put("finalPrice", mAllMoney);//所有金额
        params.put("consigneeName", mAddressee);//收件人
        params.put("consigneePhone", mPhoneNum);//手机号码
        params.put("address", mAddress);//详细地址
        params.put("orderId", mOrderIds);//订单容器
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("InvoiceAddressActivity", "提交订单: --->>" + s);

                try {
                    Invoice invoice = GsonUtils.parseJSON(s, Invoice.class);
                    if (invoice.getStatus() == 0) {
                        showSuccessDialog("申请发票成功，物流号请到开票历史查看");
                    }else{
                        ToastUtils.showShortToast(InvoiceAddressActivity.this,invoice.getMes());
                    }

                } catch (Exception e) {
                    Toast.makeText(InvoiceAddressActivity.this, "数据解析错误" , Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("InvoiceAddressActivity", "提交失败");
                Toast.makeText(InvoiceAddressActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 提交成功
     */
    private void showSuccessDialog(String mes) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(InvoiceAddressActivity.this, mes, "确定");
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();

                Intent intent = new Intent(Constant.BROADCASTCODE.INVOICE);

                sendBroadcast(intent);
                finishTo();

            }
        });
        singleBtnDialog.show();

    }

    /**
     * 地址选择器
     */
    private void showAddressChoose() {
        try {
            ArrayList<AddressPicker.Province> data = new ArrayList<AddressPicker.Province>();
            String json = ConvertUtils.toString(getAssets().open("city.json"));
            data.addAll(JSON.parseArray(json, AddressPicker.Province.class));
            AddressPicker picker = new AddressPicker(this, data);
            picker.setSelectedItem("福建", "厦门", "思明");
            picker.setOnAddressPickListener(new AddressPicker.OnAddressPickListener() {
                @Override
                public void onAddressPicked(AddressPicker.Province province, AddressPicker.City city, AddressPicker.County county) {
                    if (county == null) {
                        mTv_province.setText(province.getAreaName());
                        mTv_city.setText(city.getAreaName());
                    } else {
                        mTv_province.setText(province.getAreaName());
                        mTv_city.setText(city.getAreaName());
                        mTv_town.setText(county.getAreaName());
                        mBasicAddress = province.getAreaName() + city.getAreaName() + county.getAreaName();
                    }
                }
            });
            picker.show();
        } catch (Exception e) {
            Toast.makeText(this, "出错了", Toast.LENGTH_SHORT).show();
        }
    }
}
